﻿using MediatR;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.DAL;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Event;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Models;

namespace WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Handler
{
    //在MediatR  12+以上新版中，对同一事件的处理是无序的。
    // 物流处理程序（创建物流记录）
    public class ShippingHandler : INotificationHandler<OrderCreatedEvent>
    {
        private readonly AppDbContext _dbContext;

        public ShippingHandler(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken)
        {
            // 模拟物流创建（这里可以添加失败测试：throw new Exception("物流创建失败")）
            var shipment = new Shipment
            {
                OrderId = notification.OrderId,
                Status = "Processing",
                CreatedDate = DateTime.UtcNow
            };
            _dbContext.Shipments.Add(shipment);
            await _dbContext.SaveChangesAsync(cancellationToken);

            Console.WriteLine($"物流已创建 - 订单ID: {notification.OrderId}, 物流ID: {shipment.Id}");
        }
    }
}
